#!/bin/sh
#
# Script to install Distributed File System on Minix3
#
# This is our devel install script in fresh minix images
# it might changed a lot when we release omitting the svn stuff
# Think of a tarball with a configure like script
#
# Execute script with an optional argument of a username

SOURCE=/usr/src/
REPOURL="https://dfsminixos2ceid.googlecode.com/svn/trunk/"

do_exit()
{
	echo $1
	exit 1
}

get_source_from_subversion()
{
	echo -n "Checkout read-only version? (y/N):"
	read reply
	if test $reply = y; then
		echo 'Checking out read-only version...'
		svn co $REPOURL/src src	# readonly checkout
	else
		echo "Checking out read-write version..."
		echo "Googlecode username:"
		read username
		svn co $REPOURL/src src --username $username # full permission checkout
	fi	
}

clean_previous_install()
{
	cd $1
	echo "Cleaning previous install"
	make clean
}

prepare_makefiles()
{
	cd $1
	touch Makefile.in	# Must touch (not in a gay kinda way) the Makefile.in to
	make Makefile		# generate Makefiles
}

prepare_lib_depends()
{
	cd /usr/src/lib
	make depend
}

install_dfs()
{
	clean_previous_install $SOURCE
	echo "Installing DFS"
	# Preparing libraries
	prepare_makefiles $SOURCE/lib/dfs
	prepare_makefiles $SOURCE/lib/syscall
	prepare_makefiles $SOURCE/lib
	# Formating librarie's depends
	prepare_lib_depends
	# Compiling world
	cd /usr/src
	make depend	#prepare depends of services & cmds
	make world
}

if test x`which svn` = x; then
	do_exit "svn (subversion) is not available. Please install it and try again."
fi

if test x`which gcc` = x; then
	do_exit "gcc (Gnu Compiler Collection) is not available. Please install it and try again."
fi

if test ! -d $SOURCE/servers/dfs; then
	cd /usr
	echo "Backing up src folder to src.backup"
	mv src src.backup
	get_source_from_subversion
	echo "Retrieving the source backed up before.Press n when you asked to overwrite"
	if test -d $SOURCE/servers; then
		cp -ri src.backup/* src
		install_dfs
		do_exit "If no errors occured, just load the new system image."
	else
		echo "Error occured.Restoring source backup."
		mv  src.backup src
		do_exit "Failure!. Backup files are now set."
	fi
else
	echo "Distributed file system already installed. Updating..."
	cd $SOURCE
	svn update
	echo "Updated to latest revision."
	install_dfs
	echo "--"
	echo "Shutdown your image and boot to the latest image shown above"
	echo "Distributed File System (DFS) successfully installed"
	do_exit 
fi
